package com.bsi.core.fdfs;

import com.bsi.core.exception.BusinessException;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/*
 * Author: liusongs
 * Date: 2020/1/9 10:50
 * Content: fastDfs图片服务器配置类
 */
@Configuration
@ConfigurationProperties(prefix = "fdfs")
@RefreshScope
public class FastDFSConfig {
    // nginx的路径 此路径为上传后访问的路径
    private String nginxServer;

    // 限定上传的文件类型
    private List<String> includeExt;

    public final String GROUP = "group1";

    public String getNginxServer() {
        return nginxServer;
    }

    public void setNginxServer(String nginxServer) {
        this.nginxServer = nginxServer;
    }

    public List<String> getIncludeExt() {
        return includeExt;
    }

    public void setIncludeExt(List<String> includeExt) {
        this.includeExt = includeExt;
    }

    /**
     * 判断该文件是否能上传
     *
     * @param fileName 文件名
     * @return 是否能上传
     */
    public String isIgnore(String fileName) throws BusinessException {
        Assert.hasText(fileName, "[FastDFSConfiguration.isIgnore]->此方法调用时文件名不能为空!");

        int i = fileName.lastIndexOf(".");// 获取最后一个点出现的位置进行截取文件获得文件尾缀
        if (i == -1) {
            throw new BusinessException("[FastDFSConfiguration.isIgnore]->请传入正确的文件名,当前文件名为:" + fileName);
        }
        String ext = fileName.substring(i + 1).toLowerCase();
        if (!StringUtils.hasText(ext)) {
            throw new BusinessException("[FastDFSConfiguration.isIgnore]->请传入正确的文件名,当前文件名为:" + fileName);
        }
        if (CollectionUtils.isEmpty(includeExt)) { // 如果都为空说明没有检验限制，所有文件都可以上传
            return ext;
        }
        if (!includeExt.contains(ext)) {
            throw new BusinessException("该文件类型不支持上传,请上传正确的数据格式");
        }
        return ext;
    }


}
